#include "adduser.h"
#include "authuser.h"
#include "ui_authuser.h"
#include <iostream>
using namespace std;

AuthUser::AuthUser(QString id,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AuthUser)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/image/res/stm.jpg"));
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_hideSearch->setIcon(pix);
    ui->btn_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_refresh->setIcon(freshPix.scaled(25,25));
    ui->lineEdit_gotoPage->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*")));
    setWindowTitle("分配用户");
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);   //只能选中整行
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);    //单元格不可编辑

    this->roleId = id;
    pageNum = 1;
    pageSize = 10;
    currentPage = 1;

    init();


}

AuthUser::~AuthUser()
{
    delete ui;
}

void AuthUser::init()
{
    getList();
    initTable();
    initPageInfo();
}

void AuthUser::getList()
{
    userList.clear();
    QByteArray *data = roleManagerApi.allocatedList(pageNum,pageSize,roleId,
                ui->lineEdit_username->text(),ui->lineEdit_phone->text());
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("rows").toArray();
    total = obj.value("total").toInt();
    for(int i = 0;i< arr.size();i++){
        QJsonObject userObj = arr.at(i).toObject();
        User user = User::toUser(userObj);
        userList.append(user);
    }
    if(total % pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_count->setText("共"+QString::number(total)+"条");
}

void AuthUser::initTable()
{
    ui->tableWidget->setSortingEnabled(0);
    ui->tableWidget->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget->clear();
    QStringList columnHeader;
    columnHeader << "角色名称" << "角色昵称" << "邮箱" << "手机" << "状态" << "创建时间" << "操作" << "id";
    ui->tableWidget->setColumnCount(columnHeader.size());
    ui->tableWidget->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget->setRowCount(userList.size());
    for(int i = 0;i< userList.size();i++){
        QString userId = QString::number(userList.at(i).userId);
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(userList.at(i).userName));
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(userList.at(i).nickName));
        ui->tableWidget->setItem(i,2,new QTableWidgetItem(userList.at(i).email));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(userList.at(i).phonenumber));
        ui->tableWidget->setItem(i,7,new QTableWidgetItem(userId));
        ui->tableWidget->hideColumn(7);
        QLabel *label = new QLabel();
        label->setText(userList.at(i).status == "0" ? "正常" : "停用");
        label->setFixedSize(46,20);
        label->setAlignment(Qt::AlignCenter);
        label->setStyleSheet(userList.at(i).status == "0" ?
            "background-color:rgb(230, 242, 253);color:rgb(24, 144, 255);border:1px solid rgb(209,233,255);border-radius:3px;" :
            "background-color:rgb(255, 237, 237);color:rgb(255, 73, 73);border:1px solid rgb(255,219,219);border-radius:3px;");
        QWidget *widget = new QWidget();
        QHBoxLayout* hLayout = new QHBoxLayout(widget);
        // 设置QLabel的对齐方式为居中
        label->setAlignment(Qt::AlignCenter);
        // 将QLabel添加到QHBoxLayout和QVBoxLayout
        hLayout->addWidget(label);
        ui->tableWidget->setCellWidget(i,4,widget);
        ui->tableWidget->setItem(i,5,new QTableWidgetItem(userList.at(i).createTime));
        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *cancleAuth = new QPushButton;
        connect(cancleAuth,&QPushButton::clicked,this,[=](){
            QString param = "确定要取消【" + userList.at(i).userName + "】用户的角色吗？";
            int flag = QMessageBox::question(0,"提示",param,QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                QByteArray *bytes =  roleManagerApi.cancelAuth(userId,roleId);
                QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
                QJsonObject data = obj.value("data").toObject();
                if(obj.value("code") == 200){
                    QMessageBox::warning(0,"提示",obj.value("msg").toString());
                    getList();
                    initTable();
                    initPageInfo();
                }
            }
        });
        cancleAuth->setText("❌取消授权");
        tmp_layout->addWidget(cancleAuth);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        ui->tableWidget->setCellWidget(i,6,tmp_widget);
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget->setSortingEnabled(1);
}

void AuthUser::initPageInfo()
{
    if(currentPage == 1){
        ui->btn_pervious->setEnabled(0);
    }else{
        ui->btn_pervious->setEnabled(1);
    }
    ui->label_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_next->setEnabled(0);
    }else{
        ui->btn_next->setEnabled(1);
    }
}

void AuthUser::on_btn_close_clicked()
{
    close();
}


void AuthUser::on_btn_next_clicked()
{
    ui->btn_next->setEnabled(0);
    currentPage++;
    pageNum++;
    init();
    ui->btn_next->setEnabled(1);
    initPageInfo();
}


void AuthUser::on_btn_pervious_clicked()
{
    ui->btn_pervious->setEnabled(0);
    currentPage--;
    pageNum--;
    init();
    ui->btn_pervious->setEnabled(1);
    initPageInfo();
}


void AuthUser::on_btn_cancleAuth_clicked()
{
    QList<QTableWidgetItem*> items = ui->tableWidget->selectedItems();
    if(items.isEmpty()) return;
    int rowCount = items.size() / 5;
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget->row(items.at(i * 5));
        if(i != rowCount - 1){
            ids += ui->tableWidget->item(index,7)->text() + ",";
        }else{
            ids += ui->tableWidget->item(index,7)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","是否取消选中用户授权数据项?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QByteArray *bytes = roleManagerApi.cancelAll(roleId,ids);
    QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
    if(200 == obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        getList();
        initTable();
        initPageInfo();
    }
}


void AuthUser::on_comboBox_pageItem_currentIndexChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTable();
    initPageInfo();
}


void AuthUser::on_lineEdit_gotoPage_returnPressed()
{
    int page = ui->lineEdit_gotoPage->text().toInt();
    ui->lineEdit_gotoPage->clear();
    if(page < 1 || page > totalPage){
        ui->lineEdit_gotoPage->setStyleSheet("border:1px solid red;");
        return;
    }
    ui->lineEdit_gotoPage->setStyleSheet("");
    currentPage = page;
    getList();
    initTable();
    initPageInfo();
}


void AuthUser::on_btn_hideSearch_clicked()
{
    ui->widget_2->setHidden(!ui->widget_2->isHidden());
}


void AuthUser::on_btn_refresh_clicked()
{
    getList();
    initTable();
    initPageInfo();
}


void AuthUser::on_btn_search_clicked()
{
    init();
}


void AuthUser::on_btn_reset_clicked()
{
    ui->lineEdit_username->clear();
    ui->lineEdit_phone->clear();
    init();
}


void AuthUser::on_btn_addUser_clicked()
{
    AddUser *a = new AddUser(roleId);
    a->setAttribute(Qt::WA_DeleteOnClose);
    connect(a,&AddUser::authSuccess,this,[=](){
        init();
    });
    a->exec();
}

